extends RigidBody2D

@export var SPEED = 50
@export var direction = 1 ## 移动方向 1=向右,2=向左
@export var init_move = false ## 初始化时是否是移动状态
@export var start_move_point: Area2D # 当player进入此区域时，触发该怪物移动
var died = false
var objName := "Goomba"

@onready var animated_sprite = $AnimatedSprite2D
@onready var ray_cast_left = $RayCastLeft
@onready var ray_cast_right = $RayCastRight
@onready var damage_box = $DamageBox
@onready var hit_box = $HitBox
@onready var collision_shape_2d = $CollisionShape2D


# Called when the node enters the scene tree for the first time.
func _ready():
	#self.freeze = true
	if !init_move :
		start_move_point.body_entered.connect(_on_start_move)
	pass # Replace with function body.


func _physics_process(delta):
	if died:
		self.freeze = true
		return
	if !init_move:
		return
	if ray_cast_right.is_colliding(): 
		direction = -1 
		animated_sprite.flip_h = true
	if ray_cast_left.is_colliding():
		direction = 1
		animated_sprite.flip_h = false
	var movement = Vector2(direction * SPEED, 0) * delta
	move_and_collide(movement)
	
func _on_start_move(_body):
	print("%s 开始移动" % objName)
	init_move = true

func _on_hit_box_body_entered(_body):
	print("%s 受到来自 %s 的1伤害" % [objName,_body.name])
	_died()

func _hit_box(_body):
	print("%s 受到来自 %s 的1伤害" % [objName,_body.name])
	_died()

func _died():
	died = true
	collision_layer = 0
	animated_sprite.play("die")
	await get_tree().create_timer(0.1).timeout
	queue_free()


func _on_damage_box_body_entered(body):
	print("%s 给[%s]造成一次伤害" % [objName,body.name])
	if body == self:
		return
	if died:
		return
	body.call("take_hit",self,1)
